<template>
  <div>
    <SearchForm @search="getTableData" @reset="resetSearch">
      <el-col :span="8" :xs="24" v-show="$permiss[883]">
        <el-form-item :label="$t('所属租户')">
          <el-select
              style="width: 100%"
              v-model="page.adminUserId"
              @change="tenantChange"
              clearable
          >
            <el-option
                v-for="item in tenantList"
                :key="item.adminUserId"
                :label="item.adminName"
                :value="item.adminUserId"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24" v-show="$permiss[901]">
        <el-form-item :label="$t('投放公司')">
          <el-select
              style="width: 100%"
              v-model="page.distributorId"
              clearable
          >
            <el-option
                v-for="item in launchCompanyList"
                :key="item.id"
                :label="item.distributorName"
                :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <!--      <el-col :span="8" :xs="24">-->
      <!--        <el-form-item :label="$t('投放公司')">-->
      <!--          <el-input v-model="page.distributorName"/>-->
      <!--        </el-form-item>-->
      <!--      </el-col>-->
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('公司账号')">
          <el-input v-model="page.account"/>
        </el-form-item>
      </el-col>
      <el-col :span="8" :xs="24">
        <el-form-item :label="$t('状态')">
          <el-select
              style="width: 100%"
              v-model="page.status"
              clearable
          >
            <el-option :label="$t('启用')" :value="1"></el-option>
            <el-option :label="$t('禁用')" :value="0"></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :span="12" :xs="24">
        <el-form-item :label="$t('创建时间')">
          <el-date-picker
              v-model="page.createTimeValue"
              style="width: 100%"
              type="daterange"
              range-separator="~"
              unlink-panels
              value-format="yyyy-MM-dd"
              :start-placeholder="$t('开始时间')"
              :end-placeholder="$t('结束时间')"
          >
          </el-date-picker>
        </el-form-item>
      </el-col>
    </SearchForm>
    <el-card style="margin-top: 10px" shadow="never">
      <div style="text-align: right;margin-bottom: 10px">
        <el-button type="primary" v-show="$permiss[885]" @click="addCompany">{{ $t('新增投放公司') }}</el-button>
      </div>
      <Table :table-data="tableData"
             :loading="loading"
             :table-column="tableColumn" @handleSizeChange="(val)=>{
        page.pageSize = val
        getTableData()
      }" @handleCurrentChange="(val)=>{
        page.pageNum = val
        getTableData()
      }" :page="page">
        <el-switch slot="status" slot-scope="{row}" :disabled="!$permiss[889]" @change="changeStatus(row,$event)"
                   :value="row.status === 1"></el-switch>
        <template slot="handle" slot-scope="{row}">
          <el-button type="text" v-show="$permiss[888]" @click="editCompany(row)">{{ $t('编辑') }}</el-button>
          <el-button type="text" v-show="$permiss[891]" @click="bindLinkVisible = true,tableRows = row">{{
              $t('绑定链接')
            }}
          </el-button>
          <el-button type="text" v-show="$permiss[890]" @click="resetPassword(row)">{{ $t('重置密码') }}</el-button>
        </template>
      </Table>
    </el-card>
    <!--    添加/编辑投放公司-->
    <Dialog :visible.sync="companyVisible.isShow" :title="companyVisible.title" @cancel="companyVisible.isShow = false"
            @close="clearCompanyForm" width="40%" @confirm="companyConfirm">
      <el-form label-width="80px" ref="companyForm" :model="companyForm" :rules="companyRulesForm">
        <el-form-item :label="$t('投放公司')" prop="distributorName">
          <el-input v-model="companyForm.distributorName" :disabled="companyVisible.type === 'edit'"/>
        </el-form-item>
        <el-form-item :label="$t('公司账号')" prop="account">
          <el-input v-model="companyForm.account" :disabled="companyVisible.type === 'edit'"/>
        </el-form-item>
        <el-form-item :label="$t('联系人')">
          <el-input v-model="companyForm.contactName"/>
        </el-form-item>
        <el-form-item :label="$t('联系方式')">
          <el-input v-model="companyForm.contactPhone"/>
        </el-form-item>
        <el-form-item :label="$t('备注')">
          <el-input type="textarea" :rows="5" v-model="companyForm.remark"/>
        </el-form-item>
        <el-form-item :label="$t('状态')">
          <el-radio-group v-model="companyForm.status">
            <el-radio :label="1">{{ $t('启用') }}</el-radio>
            <el-radio :label="0">{{ $t('禁用') }}</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
    </Dialog>
    <!--     绑定链接-->
    <BindLink :bindLinkVisible.sync="bindLinkVisible" :rows="tableRows" :productList="productList"></BindLink>
  </div>
</template>

<script>
import BindLink from './bindLink'
import qs from "qs";
import {
  fetchDistributorList,
  updateStatus,
  updatePassword,
  addDistributor,
  updateDistributor,
  selectCompany
} from '@/api/channel'
import {selectTenant} from "@/api/system";
import {dateFormatSection} from "@/utils/tools";

export default {
  name: 'deliveryChannelList',
  data() {
    return {
      tenantList: [],
      page: {
        pageNum: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      tableColumn: [
        {label: this.$t('投放公司'), prop: 'distributorName', align: 'center', minWidth: 100},
        {label: this.$t('公司账号'), prop: 'account', align: 'center', minWidth: 100},
        {label: this.$t('联系人'), prop: 'contactName', align: 'center', minWidth: 100},
        {label: this.$t('联系方式'), prop: 'contactPhone', align: 'center', minWidth: 100},
        {label: this.$t('备注'), prop: 'remark', align: 'center', minWidth: 150},
        {label: this.$t('创建人'), prop: 'founder', align: 'center', minWidth: 100},
        {label: this.$t('创建时间'), prop: 'inputTime', align: 'center', minWidth: 150},
        {label: this.$t('所属租户'), prop: 'adminUserName', align: 'center', minWidth: 100},
        {label: this.$t('状态'), prop: 'status', slot: 'status', align: 'center', minWidth: 100},
        {
          label: this.$t('操作'),
          slot: 'handle',
          align: 'center',
          minWidth: 200,
          isHide: !this.$permiss[887],
          fixed: 'right'
        },
      ],
      companyVisible: {
        type: '',
        title: '',
        isShow: false
      },
      companyForm: {
        status: 1
      },
      bindLinkVisible: false,
      tableRows: {},
      productList: [],
      companyRulesForm: {
        distributorName: [
          {required: true, message: this.$t('不能为空'), trigger: 'blur'},
        ],
        account: [
          {required: true, message: this.$t('不能为空'), trigger: 'blur'},
        ],
      },
      launchCompanyList: [],
      loading:false
    }
  },
  components: {
    BindLink
  },
  mounted() {
    this.getTableData()
    this.getSelect()
  },
  methods: {
    async getTableData() {
      const [startTime, endTime] = dateFormatSection(this.page.createTimeValue || [])
      const params = {
        ...this.page,
        startTime, endTime
      }
      delete params.createTimeValue
      this.loading = true
      const res = await fetchDistributorList(params)
      if (res.code === 1) {
        const {list,total} = res.data
        this.tableData = list
        this.loading = false
        this.page = {
          ...this.page,
          total
        }
      }
    },
    changeStatus({status, id}, value) {
      const title = value ? this.$t('启用后，该渠道下的所有启用状态的投放链接都将恢复可访问状态') + '!' : this.$t('禁用后，该渠道下的所有投放链接都将失效') + '!'
      const confirm = async () => {
        const res = await updateStatus(qs.stringify({
          id,
          status: status === 1 ? 0 : 1
        }))
        if (res.code === 1) {
          this.$message.success(this.$t('操作成功'))
          this.getTableData()
        }
      }
      this.$confirm(title, this.$t('提示'), {
        type: 'warning'
      }).then(() => {
        confirm()
      }).catch(() => {

      });
    },
    // 新增投放公司
    addCompany() {
      this.companyVisible = {
        type: 'add',
        title: this.$t('新增投放公司'),
        isShow: true
      }
    },
    // 编辑投放公司
    editCompany(rows) {
      this.companyForm = {...rows}
      this.companyVisible = {
        type: 'edit',
        title: this.$t('编辑投放公司'),
        isShow: true
      }
    },
    resetPassword({id}) {
      this.$confirm(this.$t('确定重置密码?'), this.$t('提示'), {
        type: 'warning'
      }).then(async () => {
        const res = await updatePassword({id})
        if (res.code === 1) {
          this.$message({
            type: 'success',
            message: this.$t('重置成功')
          });
          this.getTableData()
        }
      }).catch(() => {
      });
    },
    companyConfirm() {
      this.$refs.companyForm.validate(async v => {
        if (v) {
          const type = this.companyVisible.type
          const {id, account, contactName, contactPhone, distributorName, remark, status} = this.companyForm
          const params = {
            id, account, contactName, contactPhone, distributorName, status, remark
          }
          const api = (params) => type === 'add' ? addDistributor(params) : updateDistributor(params)
          const res = await api(qs.stringify(params))
          if (res.code === 1) {
            const message = type === 'add' ? this.$t('新增成功') : this.$t('编辑成功')
            this.$message.success(message)
            this.companyVisible.isShow = false
            this.getTableData()
          }
        }
      })
    },
    // 获取投放公司
    async getLaunchCompany() {
      const res = await selectCompany({adminUserId: this.page.adminUserId})
      if (res.code === 1) {
        this.launchCompanyList = res.data
      }
    },
    resetSearch() {
      this.page = {
        pageNum: 1,
        pageSize: 10,
        total: 0
      }
      this.getTableData()
    },
    // 租户下拉切换
    tenantChange() {
      if (this.page.distributorId) {
        this.$set(this.page, 'distributorId', null)
      }
      this.getLaunchCompany()
    },
    clearCompanyForm() {
      this.companyForm = {
        status: 1
      }
      this.$refs.companyForm.resetFields()
    },
     getSelect() {
      this.getLaunchCompany()
      selectTenant().then(res => {
        this.tenantList = res.data
      })
    }
  }

}
</script>

<style scoped>

</style>
